package com.linkoog.devtools.toolwindow_manager;

import com.intellij.openapi.ui.ComboBox;

import javax.swing.*;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;

/**
 *
 */
class AvailabilityPreferenceJTable extends JTable {
    static final int TOOL_WINDOW_ID_COLUMN_INDEX = 0;
    static final int AVAILABILITY_PREFERENCE_COLUMN_INDEX = 1;

    private final TableCellEditor availabilityPreferenceCellEditor =
            new DefaultCellEditor(new ComboBox(AvailabilityPreference.values(), 120));

    AvailabilityPreferenceJTable() {
        super();
    }

    @Override
    public void createDefaultColumnsFromModel() {
        super.createDefaultColumnsFromModel();
        getColumn(getColumnName(AVAILABILITY_PREFERENCE_COLUMN_INDEX)).setPreferredWidth(200);
        getColumn(getColumnName(TOOL_WINDOW_ID_COLUMN_INDEX)).setPreferredWidth(400);
    }

    @Override
    protected TableModel createDefaultDataModel() {
        return new AvailabilityPreferenceTableModel();
    }

    @Override
    protected ListSelectionModel createDefaultSelectionModel() {
        final ListSelectionModel listSelectionModel = new DefaultListSelectionModel();

        listSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        return listSelectionModel;
    }

    @Override
    protected JTableHeader createDefaultTableHeader() {
        final JTableHeader defaultTableHeader = super.createDefaultTableHeader();

        defaultTableHeader.setReorderingAllowed(false);

        return defaultTableHeader;
    }

    @Override
    public TableCellEditor getCellEditor(final int row, final int column) {
        final TableCellEditor result;

        if (column == AVAILABILITY_PREFERENCE_COLUMN_INDEX) {
            result = availabilityPreferenceCellEditor;
        } else {
            result = super.getCellEditor(row, column);
        }

        return result;
    }

    @Override
    public TableCellRenderer getCellRenderer(int row, int column) {
        final TableCellRenderer result;
        final AvailabilityPreference availabilityPreference =
                (AvailabilityPreference) getValueAt(row, AvailabilityPreferenceJTable.AVAILABILITY_PREFERENCE_COLUMN_INDEX);

        switch (availabilityPreference) {
            case AVAILABLE:
                result = ToolWindowPreferenceCellRenderer.AVAILABLE;
                break;
            case UNAFFECTED:
                result = ToolWindowPreferenceCellRenderer.UNAFFECTED;
                break;
            case UNAVAILABLE:
                result = ToolWindowPreferenceCellRenderer.UNAVAILABLE;
                break;
            default:
                result = null; // Should never be reached
        }

        return result;
    }
}
